package io.zhifei.modules.sys.system.util;

import com.alibaba.druid.util.StringUtils;
import io.zhifei.modules.app.login.entity.Tree;
import io.zhifei.modules.sys.system.entity.user.MenuInfoResult;

import java.util.ArrayList;
import java.util.List;

/**
 * <p> 生成树形图 </p>
 *
 * @author： WangPeng <br/>
 * @date： 2020/8/31$ 16:07$ <br/>
 * @version： <br/>
 */
public class UserToTree {

    public static <T extends UserTree> List<T> listToTree(List<T> list) {


        List<T> nodeList = new ArrayList<>();
        for (T node : list) {
            if (node.getChildren() == null){
                node.setChildren((new ArrayList<>()));
            }
            boolean mark = false;
            for (T node2 : list) {
                if (node.getPid() != null && node.getPid().equals(node2.getId())) {
                    mark = true;
                    if (node2.getChildren() == null) {
                        node2.setChildren((new ArrayList<>()));
                    }
                    node2.getChildren().add((MenuInfoResult) node);
                    break;
                }
            }
            if (!mark && isRoot(node.getPid().toString())) {
                nodeList.add(node);
            }
        }
        return nodeList;
    }


    private static boolean isRoot(String pid) {
        if (StringUtils.isEmpty(pid)) {
            return true;
        }
        if ("0".equals(pid)) {
            return true;
        }
        return false;
    }
}
